<template>
  <div v-loading="isLoadDetail" :class="{'mobile-supplier-create': showMobilePage}" class="pay-application-container">
    <template v-if="!permissionDenied">
      <!-- 进度条, 成本选择(0) 审批项选择(1) 请款审批(2) 结算完成(4) -->
      <Step v-if="!showMobilePage" :process="process"/>
      <!-- 状态图标 pageStatus: 状态, 等待(0) 完成(1) 撤回(2) -->
      <div v-if="pageStatus === 1 || pageStatus === 2" class="status-icon">
        <img :src="pageStatus === 1?success:close" alt="success">
      </div>
      <!-- 结算信息: 只有成本选择(0) 审批项选择(1)才显示 -->
      <SettleInfo
        v-if="process === 0 || process === 1"
        ref="settleInfoRef"
        v-model="stepOneData"
        :process="process"
        @changeValue="supplierChange"
      />
      <!-- 每一步功能写在这 -->
      <!-- 1、成本选择 -->
      <CostSelect
        v-if="process === 0 && !resetCostSelect"
        ref="costSelectRef"
        v-model="stepOneData.costBelong"
        :process="process"
        :step-one-data="stepOneData"
        @settleInfoValid="settleInfoValid"
        @costSelectCallback="costSelectCallback" />
      <!-- 2、订单选择 -->
      <OrderSelect
        v-if="process === 1"
        v-model="stepTwoData"
        :step-one-data="stepOneData"
        :settle-id="settleId"
        :is-edit="isEdit"
        @setStepId="setStepId"
        @selectCallback="selectCallback"/>
      <!-- 3、付款申请 -->
      <PayApplication
        v-if="process === 2"
        ref="payApplicationRef"
        v-model="stepThreeData"
        :step-two-data="stepTwoData"
        :step-one-data="stepOneData"
        :settle-id="settleId"
        :is-not-order="isNotOrder"
        :is-edit="isEdit"
        @setStepId="setStepId"
        @reApplyAfterCall="reApplyAfterCall"
      />
    </template>
    <div v-else class="flex">
      <DeniedPlaceholder />
    </div>
    <div class="debug-console" @click="testConsole">console</div>
  </div>
</template>
<script>
// components
import Step from '@/components/SupplierComponent/step';
import SettleInfo from './model/settleInfo.vue';
import CostSelect from './model/costSelect';
import OrderSelect from './model/orderSelect/index';
import PayApplication from './model/payApplication';
// api
import { currentWidthdrawInfo, examineList as getExamineList, getSupplierDetail } from '@/api/supplier';
import { getContractDetail } from '@/api/legal';
// utils
import InitMethods from './mixins/createInitMethods.js';
import mobileCreate from '@/mixins/mobileCreate';
// img
import success from '@/assets/auditProcess/process_status_4.png';
import close from '@/assets/auditProcess/process_status_6.png';
import pressImg from '@/assets/press_top.png';
import pressCancelImg from '@/assets/press_cancel.png';
export default {
  components: { Step, SettleInfo, CostSelect, OrderSelect, PayApplication },
  mixins: [InitMethods, mobileCreate],
  inject: ['_reloadPage'],
  data() {
    return {
      success, close, pressImg, pressCancelImg,
      // 步骤1 成本选择的数据
      stepOneData: {
        selectCost: [],
        costBelong: null, // 成本归属 0:销售成本 2:萌力成本 6:有赞成本
        pageFrom: null, // 供应商来源
        supplierId: '', // 供应商id
        supplierName: '', // 供应商名称
        settlementMethod: null, // 结算方式
        isInvite: false // 协作方式
      },
      // 步骤2 审批项选择的数据
      stepTwoData: {
        cost: []
      },
      // 步骤3 付款申请的数据
      stepThreeData: {},

      isNotOrder: false,
      process: 0, // 控制进度条, 成本选择(0) 审批项选择(1) 请款审批(2) 结算完成(4)
      pageStatus: null, // 状态, 等待(0) 完成(1) 撤回(2)
      permissionDenied: false, // 详情页是否可查看
      resetCostSelect: false,
      isLoadDetail: false,
      examineList: [], // 审批记录列表
      settleId: '',
      examineId: '',
      firstSupplierId: null, // 自动填充该id的请款单合同信息和发票信息
      isEdit: false,
      isAccountSettle: false // 是否为待办账号结算
    };
  },
  provide() {
    return {
      // 待办，账号结算时进行填充
      setSettleId: ({ settleId, supplierId, costBelong }) => {
        this.stepOneData.supplierId = supplierId;
        this.stepOneData.costBelong = costBelong;
        this.settleId = settleId;
      },
      // 协作请款需要动态获取 isExamineing 和 isExamined
      getIsExamineing: () => this.isExamineing,
      getIsExamined: () => this.isExamined,
      // 协作订单刷新数据用
      freshDetail: this.getDetail
    };
  },
  computed: {
    isInvite() { // 是否为协作请款
      return !!this.stepOneData.isInvite;
    },
    isExamineing() {
      // 审批记录中是否存在审批中的记录
      const examineList = this.examineList;
      if (examineList && examineList.length) {
        return examineList.some(i => i.examineStatus === 1);
      }
      return false;
    },
    isExamined() {
      // 审批记录中是否存在已完成的记录
      const examineList = this.examineList;
      if (examineList && examineList.length) {
        return examineList.some(i => i.examineStatus === 4);
      }
      return false;
    }
  },
  /**
   * 路由 query 参数列表
   * id: 供应商id
   * examineId: 审批单id
   * supplierId: 供应商id
   * settleId: 结算id
   * isInvite: 是否为协作请款
   * isSettle: 是否调用供应商详情接口（旧逻辑，可废弃）
   * isAccountSettle: 是否待办详情账号结算
   *
   * costItemId: 成本项id
   * name: 成本项名称
   * costId: 成本ID
   * relatedOrderId: 关联订单ID
   * orderId: 订单编号
   * costBelong: 成本来源
   *
   * isNotOrder: 非订单请款

      isLaunchExamine 在同一个结算单上发起一个新的审批单 isLaunchExamine 1:发起审批，不会填内容 2:申请余款，回填内容
   * isLaunchExamine: 发起审批入口。在同一个结算单上发起一个新的审批单
   */
  created() {
    this.settleId = Number(this.$route.query.settleId) || 0; // 结算id
    const examineId = Number(this.$route.query.examineId) || 0; // 审批单id
    const createNew = Number(this.$route.query.createNew) || 0; // 再次发起（复制）
    if (this.$route.query.costItemId) { // 从成本过来,默认多次结算
      this.stepOneData.settlementMethod = 0;
    }
    // 在同一个结算单上发起一个新的审批单 isLaunchExamine 1:发起审批，不会填内容 2:申请余款，回填内容
    const isLaunchExamine = !!Number(this.$route.query.isLaunchExamine || 0);
    // 多次结算的结算单，在已有审批单的情况下，新建审批单时，复用创建时间最早的审批单的合同信息、发票信息
    if (this.$route.query.firstSupplierId) {
      this.firstSupplierId = this.$route.query.firstSupplierId;
    }
    if (!createNew && !!(examineId || isLaunchExamine)) {
      this.isEdit = !isLaunchExamine;
      this.examineId = examineId;
      this.getDetail();
    } else {
      this.stepOneData.isInvite = !!this.$route.query.isInvite;
      this.isNotOrder = !!this.$route.query.isNotOrder; // 非订单请款
      // 初始化方法在 ./createInitMethods 中
      this.initMethod();
    }
    if (this.isInvite) {
      this.getExamineList();
    }
    if (this.$route.query.legalId) {
      this.initSettleInfo(this.$route.query.legalId);
    }
  },
  methods: {
    /**
     * change
     */
    // 供应商来源 或 供应商名称 改变
    supplierChange() {
      const { pageFrom, supplierId, legalSupplierId } = this.stepOneData;
      if (pageFrom === 'saleSupplier') this.stepOneData.costBelong = 0;
      if (pageFrom === 'mengliSupplier') this.stepOneData.costBelong = 2;
      if (supplierId) {
        if (this.$refs.costSelectRef) {
          this.$nextTick(() => {
            this.$refs.costSelectRef.getCostNums();
          });
        }
      } else {
        this.resetCostSelect = true;
        this.$nextTick(() => {
          this.resetCostSelect = false;
        });
      }
      if (legalSupplierId && legalSupplierId !== supplierId) this.stepOneData.contractCode = '';
    },
    /**
     * 获取数据
     */

    // 获取结算详情
    getDetail() {
      const params = {};
      this.isLoadDetail = true;
      if (this.isInvite) {
        params.isPermission = false;
      }
      getSupplierDetail(this.settleId, params).then(res => {
        this.isLoadDetail = false;
        if (res.code === 200) {
          this.settleDetailData = res.data;
          this.process = res.data.process;
          this.isNotOrder = res.data.isNotOrder;
          const pageFrom = res.data.costBelong === 2 ? 'mengliSupplier' : 'saleSupplier';
          this.stepOneData = {
            selectCost: res.data.selectCost,
            costBelong: res.data.costBelong,
            supplierId: res.data.supplierId,
            isInvite: res.data.isInvite,
            settlementMethod: this.$route.query.isAccountSettle ? 0 : res.data.settlementMethod, // 每月结算过来默认为多次结算
            pageFrom
          };
          this.stepThreeData = res.data;
          this.handleStepTwoParams(res.data);

          // 用于判断结算单完成之后展示的icon
          this.pageStatus = this.getProcessDetail(this.process).status;
          // 多次结算的结算单，在已有审批单的情况下，新建审批单时，复用第一个审批单的合同信息、发票信息
          this.autoFillOrderInfo();
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.isLoadDetail = false;
      });
    },
    autoFillOrderInfo() {
      if (this.firstSupplierId) {
        currentWidthdrawInfo(this.firstSupplierId).then(res => {
          if (this.$refs['payApplicationRef'] && this.$refs['payApplicationRef'].$refs['WithDrawForm']) {
            const { contractList, invoiceList } = res.data || {};
            contractList && contractList.forEach(item => {
              if (res.data.contractSign === 0 && item.contractSourceType === 1) {
                item.disable = true;
              }

              item.oppCompanyData = item.oppCompany ? { name: item.oppCompany, id: item.oppCompanyId, type: item.oppCompanyType } : null;
            });
            invoiceList && invoiceList.forEach(item => {
              delete item.id;
            });
            this.$refs['payApplicationRef'].$refs['WithDrawForm'].headForm.contractList = contractList || [];
            this.$refs['payApplicationRef'].$refs['WithDrawForm'].headForm.invoiceList = invoiceList || [];
          }
        });
      }
    },
    handleStepTwoParams(data) {
      if (data.selectCost.length > 0) {
        const cacheParams = {
          id: data.supplierId,
          costBelong: data.costBelong,
          cost: []
        };
        data.selectCost.forEach(i => {
          const selectOrderIds = [];
          const selectCostIds = [];
          if (i.costList.length) {
            i.costList.map(it => {
              if (it.id) {
                selectOrderIds.push(it);
              } else {
                it.id = it.orderCostItemId;
                it._isCost = true; // 是否成本
                it.costItemName = it.costName;
                !it.costItemId && (it.costItemId = it.costId);
                selectCostIds.push(it);
              }
            });
          }
          cacheParams.cost.push({
            costId: i.id,
            name: i.name,
            orderIds: selectOrderIds,
            orderCostItemIds: selectCostIds
          });
        });
        this.stepTwoData = cacheParams;
      }
    },
    getProcessDetail(process) {
      if (this.stepThreeData.processDetail) {
        const result = this.stepThreeData.processDetail.find(i => {
          return i.process === process;
        });
        return result;
      }
      return null;
    },
    async getExamineList() {
      if (!this.settleId) return;
      const params = { page: 1, perPage: 20 };
      const res = await getExamineList(this.settleId, params);
      if (res.data) {
        this.examineList = res.data.items;
      }
    },
    /**
     * 逻辑方法
     */
    // 跳转下一步 或 返回上一步
    setStepId({ process }) {
      if (process || process === 0) this.process = process;
    },
    // 选择成本回调函数
    costSelectCallback(list) {
      // this.costOrder = costOrder; // 用于获取选择的成本项是否存在订单或者成本
      // this.costNum = costNum;
      this.$set(this.stepOneData, 'selectCost', list);
      if (this.stepOneData.supplierId) this.$refs.settleInfoRef.getSupplierInfo();
      this.setStepId({ process: 1 });
    },
    // 订单选择后调用, id： 结算id
    selectCallback({ id, totalPrice, selectCost }) {
      this.settleId = id;
      this.stepThreeData.totalPrice = totalPrice;
      // 没有id说明在 审批项选择中没有生成草稿

      this.stepThreeData.selectCost = selectCost;
      this.stepThreeData.isInvite = this.stepOneData.isInvite; // 是否协作
      this.stepThreeData.settlementMethod = this.stepOneData.settlementMethod; // 结算方式
      if (id) {
        this.getExamineList();
        this.getDetail();
      }

      this.setStepId({ process: 2 });
    },
    // 发起后继续审批
    reApplyAfterCall() {
      if (this.$route.name === 'supplierCreate') {
        const isAccountSettle = !!this.$route.query.isAccountSettle;
        if (isAccountSettle) {
          delete this.$route.query.isAccountSettle;
        }
        // 从哪里发起结算, saleSupplier:销售供应商列表  mengliSupplier:萌力供应商列表
        let pageFrom = 'saleSupplier';
        const costBelong = this.stepOneData.costBelong;
        if (costBelong === 0) pageFrom = 'saleSupplier';
        if (costBelong === 2) pageFrom = 'mengliSupplier';
        if (costBelong === 6) pageFrom = 'commerceSupplier';
        this.$route.query.id = this.stepOneData.supplierId;
        this.$route.query.from = pageFrom;
        this.$router.push({
          name: 'supplierCreate',
          query: {
            id: this.stepOneData.supplierId,
            from: pageFrom
          }
        });
        this._reloadPage && this._reloadPage();
      } else {
        const isNotOrder = !!this.$route.query.isNotOrder;
        const isInvite = !!this.isInvite;
        const id = this.$route.query.id;
        const from = this.$route.query.from;
        const query = { };
        if (isNotOrder) query.isNotOrder = 1;
        if (isInvite) query.isInvite = 1;
        if (id) query.id = id;
        if (from) query.from = from;
        this.$router.push({
          name: 'supplierCreate',
          query
        });
      }
    },
    async settleInfoValid() {
      const valid = await this.$refs.settleInfoRef.validateForm().catch(err => { console.log(err); });
      if (valid) {
        this.$refs.costSelectRef.launchDialog();
      } else {
        this.$message.error('请检查信息是否填写完整');
        return;
      }
    },
    async initSettleInfo(legalId) {
      const res = await getContractDetail(legalId);
      if (res.code === 200) {
        const { oppCompanyId, oppCompany, oppCompanyType, code } = res.data.contractInfo;
        this.$set(this.stepOneData, 'pageFrom', oppCompanyType === 0 ? 'saleSupplier' : 'mengliSupplier');
        this.stepOneData.pageFrom = oppCompanyType === 0 ? 'saleSupplier' : 'mengliSupplier';
        this.$nextTick(() => {
          this.stepOneData.supplierId = oppCompanyId;
          this.stepOneData.legalSupplierId = oppCompanyId;
          this.stepOneData.supplierName = oppCompany;
          this.stepOneData.settlementMethod = 0;
          this.stepOneData.contractCode = code;
          this.$refs.settleInfoRef.getSupplierInfo(true);
        });
      }
    },
    testConsole() {
      console.log('stepOneData', this.stepOneData);
      console.log('stepTwoData', this.stepTwoData);
      console.log('stepThreeData', this.stepThreeData);
    }
  }
};
</script>
<style lang="scss" scoped>
@mixin absoluteStyle($t: '', $r: '', $b: '', $l: '', $width: '', $height: '') {
  position: absolute;
  @if($t != '') {top: $t;}
  @if($r != '') {right: $r;}
  @if($b != '') {bottom: $b;}
  @if($l != '') {left: $l;}
  @if($width != '') {width: $width;}
  @if($height != '') {height: $height;}
}
.pay-application-container {
  margin: 16px;
  background-color: #fff;
  min-height: calc(100vh - 48px - 32px);
  position: relative;
  padding-bottom: 50px;
}
.debug-console {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 12px;
  cursor: pointer;
  opacity: 0;
}
.press-img{
  @include absoluteStyle($t: 0, $l: 0, $width: 86px, $height: 75px);
  z-index: 999;
}
.status-icon {
  @include absoluteStyle($t: 64px, $r: 30px, $width: 80px, $height: 80px);
  z-index: 100;
  img {
    width: 100%;
  }
}
.mobile-supplier-create {
  border-radius: 4px;
}
</style>
